package org.zpmis.domain.wechat.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.dubbo.config.annotation.Service;
import org.zpmis.common.result.PlatformResult;
import org.zpmis.domain.wechat.service.WxAuthMpService;

@Slf4j
@Service
public class WxAuthMpServiceImpl implements WxAuthMpService {

    /**
     * 微信公众号API的Service
     */
    private final WxMpService wxMpService;

    /**
     * 构造注入
     */
    WxAuthMpServiceImpl(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }

    @Override
    public String getOpenIdByCode(String code) {
        WxOAuth2AccessToken wxOAuth2AccessToken;
        try {
            log.info("[WxAuthMpServiceImpl]--getOpenIdByCode--,code:{}",code);
            //根据sdk文档 通过code获得令牌与openid
            wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("微信获得access_token异常:{}",e.getError().getErrorMsg());
            return "error";
        }

        try {
            //获得用户信息
            WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
            log.info("获得用户信息:{}",wxMpUser.toString());
            //返回用户信息
            return wxMpUser.getOpenid();
        } catch (WxErrorException e) {
            e.printStackTrace();
            return "error";
        }
    }
}
